<!-- search.php -->
<?php
include('../resource/db/db.php');

$search_term = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $search_term = $_POST['search_term'];
    $sql = "SELECT sets.*, users.username AS creator 
            FROM sets 
            JOIN users ON sets.user_id = users.user_id 
            WHERE (sets.name LIKE '%$search_term%' OR sets.info LIKE '%$search_term%') AND sets.is_deleted=0";
    $result = $conn->query($sql);
    echo $conn->error;
} else {
    $result = [];
}
?>

<!DOCTYPE html>
<html>

<head>
    <title>搜索卡组</title>
    <link rel="stylesheet" href="../resource/css/styles.css">
    <style>
        .set-info {
            display: flex;
            flex-direction: column;
        }

        .set-link {
            text-decoration: none;
            color: inherit;
        }

        .set-link:hover {
            text-decoration: underline;
        }

        .count {
            display: flex;
            justify-content: space-between;
        }

        .list-group-item {
            cursor: pointer;
        }

        .list-group-item:hover {
            background-color: #f0f0f0;
        }
    </style>
    <script>
        function goToSetPage(setId) {
            window.location.href = '../learn/set.php?set_id=' + setId;
        }
    </script>
</head>

<body>
    <?php include('../resource/navbar.php'); ?>
    <div class="container">
        <h2>搜索</h2>
        <form method="post" action="">
            <div class="form-group">
                <label for="search_term">搜索内容:</label>
                <input type="text" id="search_term" name="search_term" value="<?php echo htmlspecialchars($search_term); ?>" required>
            </div>
            <button type="submit" class="btn btn-primary">搜索</button>
        </form>
        <ul class="list-group">
            <?php

            if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                if ($result->num_rows > 0) {
                    while ($row = $result->fetch_assoc()) {
                        echo "<li class='list-group-item' onclick='goToSetPage(\"" . $row['set_id'] . "\")'>";
                        echo "<div class='set-info'>";
                        echo "<a href='../learn/set.php?set_id=" . $row['set_id'] . "' class='set-link'>";
                        echo "<h3>" . htmlspecialchars($row['name']) . "</h3></a>";
                        echo "<div class='info'>" . htmlspecialchars($row['info']) . "</div>";
                        echo "<div class='count'>";
                        echo "<span>创建者: " . htmlspecialchars($row['creator']) . "</span>";
                        echo "<span>热度: " . $row['reward'] . "</span>";
                        echo "</div>";
                        echo "</div>";
                        echo "</li>";
                    }
                } else {
                    echo "<li class='list-group-item'>没有找到相关内容</li>";
                }
            }
            ?>
        </ul>
    </div>
</body>

</html>
